<?php

namespace addons\TinyShop\merchant\forms;

use Yii;
use common\enums\StatusEnum;
use common\helpers\ArrayHelper;
use addons\TinyShop\common\models\base\LocalDistributionConfig;

/**
 * Class LocalDistributionConfigForm
 * @package addons\TinyShop\merchant\forms
 * @author jianyan74 <751393839@qq.com>
 */
class LocalDistributionConfigForm extends LocalDistributionConfig
{
    /**
     * @var array
     */
    public $discounts = [[]];

    public function init()
    {
        parent::init();

        $this->discounts = LocalDistributionConfig::find()
            ->where(['is_start' => StatusEnum::DISABLED])
            ->andWhere(['merchant_id' => Yii::$app->services->merchant->getId()])
            ->orderBy('order_money')
            ->asArray()
            ->all();
    }

    public function rules()
    {
        $rule = parent::rules();
        $rule[] = ['discounts', 'safe'];
        $rule[] = [['forenoon_start', 'forenoon_end', 'afternoon_start', 'afternoon_end'], 'required'];
        $rule[] = [['forenoon_start', 'forenoon_end', 'afternoon_start', 'afternoon_end'], 'compareHour'];

        return $rule;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        // 优惠配送金额
        return ArrayHelper::merge(parent::attributeLabels(), [
            'discounts' => '优惠配送金额'
        ]);
    }

    /**
     * @param $attribute
     */
    public function compareHour($attribute)
    {
        if ($this->forenoon_start > $this->forenoon_end) {
            $this->addError('forenoon_start', '开始时间不能大于结束时间');
        }

        if ($this->afternoon_start > $this->afternoon_end) {
            $this->addError('afternoon_start', '开始时间不能大于结束时间');
        }
    }

    /**
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        LocalDistributionConfig::deleteAll(['merchant_id' => $this->merchant_id, 'is_start' => StatusEnum::DISABLED]);
        if (!empty($this->discounts)) {
            foreach ($this->discounts as $discount) {
                if (!empty($discount)) {
                    $model = new LocalDistributionConfig();
                    $model->attributes = $discount;
                    $model->save();
                }
            }
        }

        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
    }
}